package com.heeexy.example.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.IoUtils;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heeexy.example.dao.ClassInfoDao;
import com.heeexy.example.dao.UserDao;
import com.heeexy.example.dto.TeacherInfo;
import com.heeexy.example.entity.StudentInfo;
import com.heeexy.example.dao.StudentDao;
import com.heeexy.example.util.CommonUtil;
import com.heeexy.example.util.constants.ErrorEnum;
import com.heeexy.example.util.file.ReadExcel;
import com.heeexy.example.util.listener.EmployeeReadListener;
import com.heeexy.example.util.model.response.PageResult;
import com.heeexy.example.util.model.response.QueryPageBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class StudentService {

    @Autowired
    StudentDao studentDao;

    @Autowired
    ClassInfoDao classInfoDao;

    @Autowired
    UserDao userDao;

    /**
     * 定义全局的常量值()
     */
    private static final String XLS = "xls";
    /**
     * 定义全局的常量值
     */
    private static final String XLSX = "xlsx";
    /**
     * logger
     */
    //private Logger logger = LoggerFactory.getLogger(StudentService.class);

    /*
     * 查询学生列表
     * */
    public JSONObject findAll(String c_id){
//        CommonUtil.fillPageParam(jsonObject);
//        int count = studentDao.countUser(jsonObject);
//        System.out.println("====="+studentDao.findAll().toString());
        c_id = "13计科";
        List<JSONObject> list = studentDao.findAll(c_id);
        return CommonUtil.successPage(list);
    }

    /*
     * 分页查询
     * */
    public PageResult findPage(QueryPageBean queryPageBean,Integer s_classid) {
        // 使用静态方法，pageheleper
        queryPageBean.setCurrentPage(1);
        queryPageBean.setPageSize(2);
        queryPageBean.setQueryString("147");
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        if(!StringUtils.isEmpty(queryPageBean.getQueryString())){
            // 模糊查询 %
            queryPageBean.setQueryString(queryPageBean.getQueryString());
        }
        // 紧接着的查询语句会被分页
        // Page 是pageHelper对象, 分页信息
        s_classid = 1;
        Page<StudentInfo> page = studentDao.findByCondition(queryPageBean.getQueryString(),s_classid);
        // 包装到PageResult 再返回
        // 1. 解耦
        // 2. total是基本类型，丢失。
        // 3. page对象内容过多 total,rows
        return new PageResult(page.getTotal(), page.getResult());
    }


    /*
     * 删除学生
     * */
    public int deleteById(int sId){
        return studentDao.deleteById(sId);
    }

    /*
     * 新增学生（学号）或外来人员（手机号当做学号）
     * */
    public JSONObject addStudent(JSONObject jsonObject){

        int exist = studentDao.queryExistStudentname(jsonObject);
        int count = classInfoDao.findByIdToMaxCount(jsonObject);
        int students = studentDao.countStudentsByClassId(jsonObject);
        if (exist > 0) {
            return CommonUtil.errorJson(ErrorEnum.E_10012);
        }
        if (students>=count){
            return CommonUtil.successJson(ErrorEnum.E_10020);
        }
        studentDao.addStudent(jsonObject);
        return CommonUtil.successJson(ErrorEnum.E_10015);
    }

    /*
     * 根据用户名/学号/手机号进行查询
     * */
    public JSONObject findQuerySnameOrSnumberOrStelephone(JSONObject jsonObject) {
        CommonUtil.fillPageParam(jsonObject);
        int countStudents = studentDao.countStudents(jsonObject);
        List<JSONObject> bySNameOrSnumberOrStelephone = studentDao.findBySNameOrSnumberOrStelephone(jsonObject);
        return CommonUtil.successPage(jsonObject, bySNameOrSnumberOrStelephone, countStudents);
    }

    /**
     * 导入教师xls
     * @param file
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveStudentXls(MultipartFile file) throws IOException {
        InputStream inputStream = null;
        try{
            inputStream=file.getInputStream();

            //获取原始文件名
            String oldFileName = file.getOriginalFilename();
            //获取文件后缀名
            String extension = "."+ FilenameUtils.getExtension(oldFileName);
            //生成缓存名
            String  newFileName = new SimpleDateFormat("yyyyMMddHHmmss")+ UUID.randomUUID().toString().replace("-","")+extension;
            //获取文件格式 ：application/vnd.ms-excel
            String type = file.getContentType();
            //判断文件类型，是否包含："xls"
//            if(!type.startsWith("xls")){
//                return CommonUtil.errorJson(ErrorEnum.E_415);
//            }
            //设置文件存放路径
            String realPath= ResourceUtils.getURL("classpath:").getPath()+"/static/files";
            //根据日期生成目录
            File dateDir =new File(realPath+"/"+new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            if (!dateDir.exists()) {
                dateDir.mkdirs();
            }

            //将文件信息放入数据库
            EasyExcel.read(inputStream, StudentInfo.class, new EmployeeReadListener(studentDao,userDao)).sheet().doRead();
            //处理文件上传
            file.transferTo(new File(dateDir,newFileName));
        }catch (IOException e){
            log.error("imPortXls()方法IOException报错:"+e.getMessage());
            return CommonUtil.errorJson(ErrorEnum.E_400);
        }finally {
            inputStream.close();
        }
        return CommonUtil.successJson();
    }

    /**
     * 导出教师xls
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void WriteTeacherXls(HttpServletResponse response,String c_id){
        c_id = "13计科";
        try{
            String realPath=ResourceUtils.getURL("classpath:").getPath()+"/static/files";
            //根据日期生成目录
            File dateDir =new File(realPath+"/"+new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            if (!dateDir.exists()) {
                dateDir.mkdirs();
            }
            //生成缓存名
            String  newFileName = new SimpleDateFormat("yyyyMMddHHmmss")+ UUID.randomUUID().toString().replace("-","")+".xlsx";
            List<JSONObject> studentList = studentDao.findAll(c_id);
            EasyExcel.write(new File(dateDir,newFileName), StudentInfo.class).sheet("学生Team WE").doWrite(studentList);
            FileInputStream inputStream = new FileInputStream(new File(dateDir,newFileName));
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode("学生名单","UTF-8")+".xlsx");

            ServletOutputStream outputStream =response.getOutputStream();
            IoUtils.copy(inputStream,outputStream);
            inputStream.close();
            outputStream.close();
        }catch (FileNotFoundException e){
            log.error("创建文件路径失败："+e.getMessage());
        } catch (IOException e) {
            log.error("ServletOutputStream获取流失败："+e.getMessage());
        }
    }

}
